// 修改导入语句
const { Product, Category } = require('../models');
const { Op } = require('../models').Sequelize;

// 在getProducts函数中添加排序验证
exports.getProducts = async (req, res, next) => {
    try {
        const { 
            page = 1, 
            limit = 12, 
            category, 
            search, 
            minPrice, 
            maxPrice, 
            sortBy = 'createdAt', 
            sortOrder = 'DESC', 
            featured 
        } = req.query;

        const offset = (page - 1) * limit;
        
        // 构建查询条件
        const whereClause = { isActive: true };
        
        if (category) {
            whereClause.categoryId = category;
        }
        
        if (search) {
            whereClause[Op.or] = [
                { name: { [Op.like]: `%${search}%` } },
                { description: { [Op.like]: `%${search}%` } },
                { shortDescription: { [Op.like]: `%${search}%` } }
            ];
        }
        
        if (minPrice || maxPrice) {
            whereClause.price = {};
            if (minPrice) whereClause.price[Op.gte] = minPrice;
            if (maxPrice) whereClause.price[Op.lte] = maxPrice;
        }
        
        if (featured === 'true') {
            whereClause.isFeatured = true;
        }

        // 修复排序逻辑：验证sortBy参数
        let order = [['createdAt', 'DESC']]; // 默认排序
        if (sortBy && typeof sortBy === 'string' && sortBy.trim() !== '') {
            order = [[sortBy, sortOrder.toUpperCase()]];
        }

        const { count, rows: products } = await Product.findAndCountAll({
            where: whereClause,
            include: [
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ],
            limit: parseInt(limit),
            offset: parseInt(offset),
            order: order, // 使用修复后的排序逻辑
            distinct: true
        });

        res.json({
            success: true,
            data: {
                products,
                pagination: {
                    page: parseInt(page),
                    limit: parseInt(limit),
                    total: count,
                    pages: Math.ceil(count / limit)
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 获取单个商品详情
exports.getProduct = async (req, res, next) => {
    try {
        const { id } = req.params;

        const product = await Product.findOne({
            where: { id, isActive: true },
            include: [
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name', 'description']
                }
            ]
        });

        if (!product) {
            return res.status(404).json({
                success: false,
                message: '商品不存在'
            });
        }

        // 增加浏览次数
        await product.increment('viewCount');

        res.json({
            success: true,
            data: { product }
        });
    } catch (error) {
        next(error);
    }
};

// 创建商品（管理员）
exports.createProduct = async (req, res, next) => {
    try {
        const {
            name, description, shortDescription, sku, price, originalPrice,
            stock, lowStockThreshold, weight, dimensions, tags, categoryId,
            isActive, isFeatured
        } = req.body;

        // 处理上传的图片
        let images = [];
        if (req.files && req.files.length > 0) {
            images = req.files.map(file => file.path);
        }

        const product = await Product.create({
            name,
            description,
            shortDescription,
            sku,
            price,
            originalPrice,
            stock,
            lowStockThreshold,
            weight,
            dimensions: dimensions ? JSON.parse(dimensions) : null,
            tags: tags ? JSON.parse(tags) : [],
            images,
            categoryId,
            isActive: isActive !== undefined ? isActive : true,
            isFeatured: isFeatured !== undefined ? isFeatured : false
        });

        // 获取包含分类信息的完整商品数据
        const fullProduct = await Product.findByPk(product.id, {
            include: [
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ]
        });

        res.status(201).json({
            success: true,
            message: '商品创建成功',
            data: { product: fullProduct }
        });
    } catch (error) {
        next(error);
    }
};

// 更新商品（管理员）
exports.updateProduct = async (req, res, next) => {
    try {
        const { id } = req.params;
        const updateData = { ...req.body };

        // 处理 JSON 字段
        if (updateData.dimensions) {
            updateData.dimensions = JSON.parse(updateData.dimensions);
        }
        if (updateData.tags) {
            updateData.tags = JSON.parse(updateData.tags);
        }

        // 处理新上传的图片
        if (req.files && req.files.length > 0) {
            const newImages = req.files.map(file => file.path);
            
            // 如果有现有图片，合并新图片
            const product = await Product.findByPk(id);
            if (product && product.images) {
                updateData.images = [...product.images, ...newImages];
            } else {
                updateData.images = newImages;
            }
        }

        const [updatedRowsCount] = await Product.update(updateData, {
            where: { id }
        });

        if (updatedRowsCount === 0) {
            return res.status(404).json({
                success: false,
                message: '商品不存在'
            });
        }

        const updatedProduct = await Product.findByPk(id, {
            include: [
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ]
        });

        res.json({
            success: true,
            message: '商品更新成功',
            data: { product: updatedProduct }
        });
    } catch (error) {
        next(error);
    }
};

// 删除商品（管理员）
exports.deleteProduct = async (req, res, next) => {
    try {
        const { id } = req.params;

        const deletedRowsCount = await Product.destroy({
            where: { id }
        });

        if (deletedRowsCount === 0) {
            return res.status(404).json({
                success: false,
                message: '商品不存在'
            });
        }

        res.json({
            success: true,
            message: '商品删除成功'
        });
    } catch (error) {
        next(error);
    }
};

// 获取分类列表
exports.getCategories = async (req, res, next) => {
    try {
        const categories = await Category.findAll({
            where: { isActive: true },
            order: [['sortOrder', 'ASC'], ['name', 'ASC']],
            include: [
                {
                    model: Product,
                    as: 'products',
                    attributes: ['id'],
                    where: { isActive: true },
                    required: false
                }
            ]
        });

        // 添加商品数量统计
        const categoriesWithCount = categories.map(category => ({
            ...category.toJSON(),
            productCount: category.products ? category.products.length : 0,
            products: undefined // 移除产品详情，只保留数量
        }));

        res.json({
            success: true,
            data: { categories: categoriesWithCount }
        });
    } catch (error) {
        next(error);
    }
};

// 创建分类（管理员）
exports.createCategory = async (req, res, next) => {
    try {
        const { name, description, sortOrder, isActive } = req.body;

        // 处理上传的图片
        let image = null;
        if (req.file) {
            image = req.file.path;
        }

        const category = await Category.create({
            name,
            description,
            image,
            sortOrder: sortOrder || 0,
            isActive: isActive !== undefined ? isActive : true
        });

        res.status(201).json({
            success: true,
            message: '分类创建成功',
            data: { category }
        });
    } catch (error) {
        next(error);
    }
};